package com.fr.lintcode;

public class Q963 {
    /**
     * @param E:
     *            the number of easy problems
     * @param EM:
     *            the number of "easy and medium" problems
     * @param M:
     *            the number of medium problems
     * @param MH:
     *            the number of "medium and hard" problems
     * @param H:
     *            the number of hard problems
     * @return: nothing
     */
    public long theNumberOfContests(long E, long EM, long M, long MH, long H) {
        // write your code here.
        long min = 0;
        long max = (E + EM + M + MH + H) / 3;
        while (min <= max) {
            long mid = (min + max) / 2;
            if (check(E, EM, M, MH, H, mid)) {
                min = mid + 1;
            } else {
                max = mid - 1;
            }
        }
        return Math.min(min, max);
    }

    private boolean check(long E, long EM, long M, long MH, long H, long target) {
        if (E > target) {
            M = M + EM;
        } else {
            EM = E + EM - target;
            if (EM < 0) {
                return false;
            }
            M = M + EM;
        }
        if (M > target) {
            H = H + MH;
        } else {
            MH = M + MH - target;
            if (MH < 0) {
                return false;
            }
            H = H + MH;
        }
        return H >= target;
    }

}
